package com.example.cachewebview

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.webkit.WebSettings
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ToastUtils
import com.example.cachewebview.util.UrlManager
import com.fan.cachewebview.R
import com.fan.cachewebview.pool.CacheWebView
import com.fan.cachewebview.pool.WebViewCacheHolder
import java.util.regex.Matcher
import java.util.regex.Pattern


class MainActivity : AppCompatActivity() {
    private lateinit var btnWebNormal: Button
    private lateinit var btnWebCache: Button
    private var webUrl: String = "https://sh.58.com"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initView()
        preloadUrl(UrlManager.webUrl)
    }

    private fun initView() {
        btnWebNormal = findViewById(R.id.btn_web_normal)
        btnWebCache = findViewById(R.id.btn_web_cache)

        btnWebNormal.setOnClickListener {
            if (checkUrl(webUrl)) {
                val intent = Intent(this@MainActivity, NormalWebActivity::class.java)
                intent.putExtra("url", webUrl)
                startActivity(intent)
            } else {
                ToastUtils.showShort("请输入正确的 H5地址")
            }
        }

        btnWebCache.setOnClickListener {
            if (checkUrl(webUrl)) {
                val intent = Intent(this@MainActivity, WebActivity::class.java)
                intent.putExtra("url", webUrl)
                startActivity(intent)
            } else {
                ToastUtils.showShort("请输入正确的 H5地址")
            }
        }
    }

    private fun preloadUrl(url: String) {
        val webView: CacheWebView = WebViewCacheHolder.acquire(this)
        val cacheMode = if (WebSettingUtil.isNetworkConnected(this)) WebSettings.LOAD_DEFAULT else WebSettings.LOAD_CACHE_ELSE_NETWORK
        WebSettingUtil.webSetting(webView)
        webView.settings.cacheMode = cacheMode
        webView.preload(this, url)
    }

    private fun checkUrl(url: String): Boolean {
        if (TextUtils.isEmpty(url)) {
            return false
        }
        val p: Pattern =
            Pattern.compile("(http://|https://)(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?")
        val m: Matcher = p.matcher(url)
        return m.matches()
    }
}